<?php

class Users extends App_Db_Model 
{
	public $id;
	public $name;
	public $login;
	public $passwd;
	public $blocked;
	public $blockedname;
    protected $_name = 'users';
    
	function __construct($fieldArr = null) {
		parent::__construct();
		if (is_null($fieldArr)) {
			$this->id=0;
			$this->name="";
			$this->login="";
			$this->passwd = "";
			$this->blocked = 0;
			$this->blockedname = "";
		} else {
			$this->setDataFromDBArray($fieldArr);
		}
	}
    
	public function getArrayFromData($withkey=true) {
		$fieldArr = array(
			"name" => $this->name,
			"login" => $this->login,
			"passwd" => $this->passwd,
			"blocked" => $this->blocked
		);
		if ($withkey) $fieldArr["id"] = $this->id;
		return $fieldArr;
	}
	
	public function setDataFromArray($fieldArr) {
		$this->id = $fieldArr["id"];
		$this->name = $fieldArr["name"];
		$this->login = $fieldArr["login"];
		$this->passwd = $fieldArr["passwd"];
		$this->blocked = $fieldArr["blocked"];
	}

	public function getDBArrayFromData($withkey=true) {
		$fieldArr = array(
			"name" => $this->name,
			"login" => $this->login,
			"passwd" => $this->passwd,
			"blocked" => $this->blocked
		);
		if ($withkey) $fieldArr["ID"] = $this->id;
		$fieldArr = iconvObj($fieldArr, UTF_CHARSET, CP1251_CHARSET);
		return $fieldArr;
	}
	
	public function setDataFromDBArray($fieldArr) {
		$fieldArr = iconvObj($fieldArr, CP1251_CHARSET, UTF_CHARSET);
		$this->id = $fieldArr["id"];
		$this->name = $fieldArr["name"];
		$this->login = $fieldArr["login"];
		$this->passwd = $fieldArr["passwd"];
		$this->blocked = $fieldArr["blocked"];
		$this->blockedname = (($this->blocked==1)?"блокирован":"активен");
	}
	/**
     * Получить всех авторов или одного
     *
     * @param int $authorId Идентификатор автора
     * @return array
     */
    public function getUsers() 
    {
        $select = $this->getAdapter()->select()->from($this->_name);
        $select->order("name");
		$stmt = $this->getAdapter()->query($select);
        $dataArr = $stmt->fetchAll(Zend_Db::FETCH_ASSOC);    
		$result = array();
		foreach ($dataArr as $k=>$v) {
			$result[] = new Users($v);
		}
        return $result;
    }

    public function getUser($id) {
        $select = $this->getAdapter()->select()->from($this->_name);
        $select->where($this->_name.".id = ?", $id); 
        $stmt = $this->getAdapter()->query($select);
		$dataArr = $stmt->fetch(Zend_Db::FETCH_ASSOC);
		$this->setDataFromDBArray($dataArr);
        return $this;
    }
}